package event_manager

import (
	"go_server/game_server/api/iservice"
	"go_server/game_server/event_manager/event_data"
	"go_server/zinx/zlog"
	"sync"
)

var (
	EventManagerObj *EventManager
)

type EventManager struct {
	mutex        sync.Mutex
	eventMethods map[event_data.EventType][]iservice.IService
	Wg           sync.WaitGroup
}

func init() {
	EventManagerObj = &EventManager{
		eventMethods: make(map[event_data.EventType][]iservice.IService),
	}
}

func (em *EventManager) FireEventData(eventData event_data.IEvent) {
	em.mutex.Lock()
	defer em.mutex.Unlock()
	evenType := eventData.GetEventType()
	serviceArry, ok := em.eventMethods[evenType]
	if !ok {
		zlog.Errorf("FireEventData err! not find name, eventName: %d", evenType)
		return
	}

	for _, iService := range serviceArry {
		eventFunc, ok := iService.GetEventHandleFunc(evenType)
		if !ok {
			continue
		}
		go eventFunc(eventData)
	}
}

func (em *EventManager) AddServiceEvent(eventType event_data.EventType, eventFunc func(event event_data.IEvent),
	service iservice.IService) {
	methodsMap := service.GetEventMap()
	if _, ok := methodsMap[eventType]; ok {
		zlog.Panicf("eventType repeated!!!, eventType: %d, serviceName: %s", eventType, service.GetModuleName())
	}
	methodsMap[eventType] = eventFunc

	//iserviceArray, ok := em.eventMethods[eventType]
	//if ok {
	em.eventMethods[eventType] = append(em.eventMethods[eventType], service)
	//} else {
	//	iserviceArray = make([]iservice.IService, 0, 100)
	//	iserviceArray = append(iserviceArray, service)
	//	em.eventMethods[eventType] = iserviceArray
	//}
}

func (em *EventManager) GetServerShutdownEventCount() int {
	serviceArry, ok := em.eventMethods[event_data.ServerShutdownEvent]
	if !ok {
		zlog.Errorf("FireEventData err! not find name, eventName: %d", event_data.ServerShutdownEvent)
		return 0
	}
	return len(serviceArry)
}
